//引入express模块
const express = require('express');
//引入连接池模块
const pool = require('../pool');
const multiparty = require('multiparty')


//创建路由器对象
const r = express.Router();
//引入短信SDK
 // Depends on tencentcloud-sdk-nodejs version 4.0.3 or higher
 const tencentcloud = require("tencentcloud-sdk-nodejs");
 const SmsClient = tencentcloud.sms.v20210111.Client;
 
// 引入七牛
const qiniu = require('qiniu');
var accessKey = 't3oxkZO7cZ5WLFh9dGvs_EyEFSUcnl30x2l6M2xA';    //这个值根据自己的七牛云中的密钥 
var secretKey = 'ua3zxKPyDTmCfUTaaMi2JUYD0rAcRyPnhtfjVo9V';   //这个值根据自己的七牛云中的密钥 
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
r.get('/uploadToken', function (req, res, next) {
	var options = {
		scope: 'zlllcy',    //这个值根据自己的七牛云中空间名称
	};
	var putPolicy = new qiniu.rs.PutPolicy(options);
	var token = putPolicy.uploadToken(mac);  //向七牛云发送一个接口
	res.json({token});
})


 // 短信接口
r.post("/sms",(req,res)=>{
  //获取用户输入的手机号码
  let phone = req.body.phone;
  console.log(phone);
  // 生成验证码
  var rnd="";
  for(var i=0;i<4;i++){
    rnd+=Math.floor(Math.random()*10);
  }
  const clientConfig = {
    credential: {
      secretId: "AKID0ysgP3d7XvEoP0W0SG6wkZJza5YM7nOu",
      secretKey: "Y0NhyBKOOMIA01ztkYJ0sjaN3fFoIfzG",
    },
    region: "ap-nanjing",
    profile: {
      httpProfile: {
        endpoint: "sms.tencentcloudapi.com",
      },
    },
  };
  const client = new SmsClient(clientConfig);
  const params = {
      "PhoneNumberSet": [
          `+86${phone}`
      ],
      "SmsSdkAppId": "1400559147",
      "SignName": "李有禄前端技术分享",
      "TemplateId": "1073279",
      "TemplateParamSet": [
          rnd
      ]
      // "TemplateParamSet":'123456'
  };
  client.SendSms(params).then(
    (data) => {
      console.log(data);
    },
    (err) => {
      console.error("error", err);
    }
  );
  // res.send(rnd);
  res.send(params.TemplateParamSet);
});



//用户注册接口
r.post('/register', (req, res) => {
  //console.log(md5('12345678'));
  // 获取手机号和密码信息
  let phone = req.body.phone;
  let upwd = req.body.upwd;
  let sms = req.body.sms;
  // 把upwd存入session域
  // req.session.upwd = upwd;
  console.log(phone,upwd,sms);
   //验证各项数据是否为空
  if(!phone){
    res.send({code: 401, msg: 'phone不能为空'});
    return;
  }
  if(!upwd){
    res.send({code: 402, msg: 'upwd不能为空'});
    return;
  }
  if(!sms){
    res.send({code: 403, msg: 'sms不能为空'});
    return;
  }
    //以phone为条件进行查找操作，以保证用户名的唯一性
    let sql = 'SELECT COUNT(uid) AS count FROM user WHERE phone=?';
    pool.query(sql, [phone,upwd,sms], (error, results) => {
      if (error) throw error;
      let count = results[0].count;
      if (count == 0) {
        // 将用户的相关信息插入到数据表
        sql = 'INSERT user(phone,upwd) VALUES(?,MD5(?))';
        pool.query(sql, [phone, upwd], (error, results) => {
          if (error) throw error;
          res.send({ message: 'ok', code: 200 });
        })
      } else {
        res.send({ message: 'user exists', code: 201 });
      }
    });
});

// 用户输入密码登录接口
r.post('/login', (req, res) => {
  //获取用户名和密码信息
  let phone = req.body.phone;
  let upwd = req.body.upwd;
  console.log(phone,upwd)

  let sql = 'select * from user where phone=? and upwd=md5(?)';
  pool.query(sql, [phone,upwd], (err, result) => {
    if (err) throw err;
    console.log(result);
    result.length
     ? res.send({message:'登录成功',code:200 ,result:result})
     : res.send({message:'无此用户',code:201});
  });

});

// 验证码登录接口
r.post('/codelogin', (req, res) => {
  //获取用户名和密码信息
  // let phone = req.body.phone;
  // let upwd = req.body.upwd;
  var obj = req.body;
  // 验证各项数据是否为空
  if(!obj.phone){
    res.send({code: 401, msg: 'phone不能为空'});
    return;
  }
  if(!obj.sms){
    res.send({code: 402, msg: 'sms不能为空'});
    return;
  }
  // SQL语句
  console.log(obj);
  let sql = 'SELECT * FROM user WHERE phone=?';
  pool.query(sql, [obj.phone], (error, result) => {
    if (error) throw error;
    console.log(result);
    if(result.length == 0){ //登录失败
      res.send({message:'login failed',code:201});
    } else {                 //登录成功
      res.send({message:'ok',code:200,result:result});
    }
  });

});

//修改密码接口(忘记密码)
//3.修改用户(put /)
//http://127.0.0.1:3000/user/update
r.put('/reupwd',(req,res,next)=>{
	//3.1获取post传递的数据
	let obj = req.body;
	console.log(obj);
	//3.2验证各项数据是否为空
	let i = 400;//记录状态码
	for(let k in obj){
		//每次遍历一个属性，状态码加1
		i++;
		//k代表属性名 obj[k]代表属性值
		//console.log(k,obj[k]);
		//如果属性值为空，提示属性名这项不能为空
		if(!obj[k]){
			res.send({code:i,msg:`${k}不能为空`});
			return;
		}
	}
  //以phone为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(uid) AS count FROM user WHERE phone=?';
  pool.query(sql, [obj.phone,obj.upwd,obj.sms,obj.reupwd], (error, results) => {
    console.log(results);
    if (error) throw error;
    let count = results[0].count;
    console.log(count);
    if(count == 0){
      res.send({code:201,msg:'用户不存在'});
      return;
    }
    if (count == 1) {
      sql="update user set upwd=? where phone=?";
      pool.query(sql,[obj.upwd,obj.phone],(error,result)=>{
        if (error) throw error;
        console.log(result);
        //结果是个对象，如果对象下的affectedRows的值为0说明修改失败，否则修改成功
        if(result.affectedRows == 0 ){
          res.send({code:201,msg:'修改失败'});
        }else{
          res.send({code:200,msg:'修改成功'});
        }
     }
    )}
  });
});

// 根据id查询用户信息
r.get('/avatar', (req, res) => {
    let uid = req.query.uid;
    let sql = 'select * from user where uid=?';
    // 执行sql语句
    pool.query(sql, [uid], (err, results) => {
      console.log(results);
      if (err) throw err;
      res.send({
        message: 'ok',
        code: 200,
        results: results
      })
    })
  })

//修改用户名
r.post('/updatename',(req,res)=>{
  let uid = req.body.uid;
  let uname = req.body.uname;
  let sql = "update user set uname=? where uid=?";
  console.log(uname);
    // 执行sql语句
  pool.query(sql, [uname,uid], (err, results) => {
      console.log(results);
      if (err) throw err;
      //结果是个对象，如果对象下的affectedRows的值为0说明修改失败，否则修改成功
        if( results.affectedRows > 0 ){
          res.send({code:200,msg:'修改成功'});
        }else{
          res.send({code:201,msg:'修改失败'});
        }
    })
})

//修改用户名和头像
r.post('/upavator',(req,res)=>{
  let uidd = req.body.id;
  let avator = req.body.aa;
  let sql = "update user set avator=? where uid=?";
  console.log(uidd,avator);
    // 执行sql语句
  pool.query(sql, [avator,uidd], (err, results) => {
      console.log(results);
      if (err) throw err;
      //结果是个对象，如果对象下的affectedRows的值为0说明修改失败，否则修改成功
        if( results.affectedRows > 0 ){
          res.send({code:200,msg:'修改成功'});
        }else{
          res.send({code:201,msg:'修改失败'});
        }
    })
})



//导出路由器对象
module.exports = r;